package org.fuys.coder.application;

import lombok.extern.slf4j.Slf4j;
import org.fuys.coder.domain.config.service.impl.CoderRecommendConfig;
import org.fuys.coder.common.entity.Pair;
import org.fuys.coder.common.entity.Result;
import org.fuys.coder.common.constants.RedisConstants;
import org.fuys.coder.common.exception.BaseException;
import org.fuys.coder.common.exception.BusinessException;
import org.fuys.coder.common.util.JWTUtil;
import org.fuys.coder.infrastructure.util.RedisUtil;
import org.fuys.coder.domain.auth.model.req.CommonRegisterReq;
import org.fuys.coder.domain.auth.model.req.CommonVerifyReq;
import org.fuys.coder.domain.auth.model.req.EmailSendReq;
import org.fuys.coder.domain.auth.model.req.LoginReq;
import org.fuys.coder.domain.auth.model.res.AuthFailedEnum;
import org.fuys.coder.domain.auth.model.vo.UserVo;
import org.fuys.coder.domain.auth.service.common.login.ICommonLoginService;
import org.fuys.coder.domain.auth.service.common.register.ICommonRegisterService;
import org.fuys.coder.domain.auth.service.vertify.email.EmailCodeVerify;
import org.springframework.context.ApplicationContext;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @projectName: fuys-low-coder
 * @package: org.fuys.coder.application
 * @className: CommonAuthController
 * @author: WangJing
 * @description: 用于普通的登录注册等验证的controller
 * @date: 2024/6/18 20:00
 * @version: 1.0
 */
@RequestMapping("/fuyscoder/auth")
@RestController
@Slf4j
public class CommonAuthController {

    @Resource
    private EmailCodeVerify codeVerify;

    @Resource
    private ICommonRegisterService ICommonRegisterService;

    @Resource
    private ICommonLoginService ICommonLoginService;


    @GetMapping("/emailCode")
    public Result sendEmailCode(CommonVerifyReq req){
        final int res = codeVerify.checkCaptcha(req.getUuid(),req.getCode());
        if(res!=-1){
            return Result.error(AuthFailedEnum.getByIdx(res).getMsg());
        }
        final String code = codeVerify.getCode(req.getEmail());
        codeVerify.send(new EmailSendReq(req.getEmail(),req.getMsg(),code));
        return Result.ok();
    }

    @GetMapping("/getCaptchaCode/{uuid}")
    public void getCaptchaCode(HttpServletResponse response,
                                 @PathVariable(value="uuid") String uuid){
        try {
            codeVerify.getImageCaptcha(response,uuid);
        } catch (BusinessException e) {
            e.printStackTrace();
        }
    }

    @PostMapping("/register")
    public Result register(@RequestBody CommonRegisterReq req){
        try {
            ICommonRegisterService.register(req);
        } catch (BaseException e) {
            //如果出现了BaseException（实际可能是NeedCallBackException） 表明注册过程因为一些原因失败
            //具体的错误信息 由e.getMsg呈现
            return Result.error(e.getMsg());
        }
        return Result.ok();
    }

    @PostMapping("/login")
    public Result login(@RequestBody LoginReq req){
        try {
            final Pair<Integer, UserVo> login = ICommonLoginService.doLogin(req);
            if(!login.getLeft().equals(-1)){
                return Result.error(AuthFailedEnum.getByIdx(login.getLeft()).getMsg()).data(login);
            }
            final UserVo right = login.getRight();
            right.setPassword("");
            final String jwtToken = JWTUtil.getJwtToken(right.getId(), right.getUsername());
            final Map<String,Object> map = new HashMap<>();
            map.put("token",jwtToken);
            map.put("userVo",right);
            return Result.ok().data(map);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(e.getMessage());
        }
    }

}
